5.3 Template Engines

  1. Motivations
    • We can include PHP code in an HTML file. Can we include JavaScript code in an HTML file as well?

  2. Project

  3. Learning objectives
    • Understand what templating is like
    • Use of basic features of a templating engine, EJS

  4. Prerequisites
    • Node.js
    • Express.js

  5. EJS
    • Read EJS
      • Idea?
        Tags
        Passing data (e.g., a variable of an object)?
      • Tags:
        • <% ... %> for control-flow and no output; for example,
          <% if (...) { %>
          <%- ... %>
          <% } %>
          
        • <%= ... %> HTML escapted output; e.g., " -> &#34 ;
        • <%- ... %> unescaped output
      • Browser support: ejs.render(teplatestring, data)

    • Trial 1: Let's try the next code with the EJS browser support.



    • Trial 2: Let's try the next code with the EJS browser support. Control structures in EJS code?



    • Trial 3: Let's try the next code with the EJS browser support. An EJS template file/string can be obtained from a server or local file system.



  6. EJS with Express
    • Read Using EJS with Express
      • ./views - a default directory for template files; file extension: .ejs
      • app.set('view engine', 'enginename')
      • res.render('templatefile', data)

    • Trial 4: Let's try the next code that uses EJS with Express.

      Connect to cs.tru.ca with your account, save the above code in views/weather.ejs and test_weather.js, and complete and run it.
      (Note that if the directory, views, does not exist, you need to create it.)
      (Note that you might need to install ejs and express.)
      How to test it?


  7. References for further information